package jdbc;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * @author huangliusong
 * @since 2018/11/2
 * {@link }
 */

public class JdbcUtil {
    /**
     * 提交事务
     * @param connection
     */
    public static void commit(Connection connection){
        if (null!=connection){
            try {
                connection.commit();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void rollback(Connection connection){
        if (null!=connection){
            try {
                connection.rollback();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void begin(Connection connection){
        if (null!=connection){
            try {
                connection.setAutoCommit(false);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static Connection getConnection() throws IOException, ClassNotFoundException, SQLException, IllegalAccessException, InstantiationException {
        Properties properties=new Properties();
        InputStream is=JdbcUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
        properties.load(is);
        String driver=properties.getProperty("jdbc.driver");
        String username=properties.getProperty("jdbc.username");
        String password=properties.getProperty("jdbc.password");
        String url=properties.getProperty("jdbc.url");
        Class.forName(driver).newInstance();
        System.out.println(driver+" "+url);
        return DriverManager.getConnection(url,username,password);
    }

    public static void closeResources(Connection connection, Statement statement, ResultSet resultSet){
        if (null!=connection){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

            if (null!=statement){
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (null!=resultSet){
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
